package com.yunshipei.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.iflytek.base.speech.adapter.AsrListener;
import com.iflytek.base.speech.adapter.AsrResult;
import com.iflytek.base.speech.adapter.SpeechRecognizerExt;
import com.iflytek.base.speech.interfaces.RecognizerIntent;
import com.yunshipei.adapter.NotificationAdapter;
import com.yunshipei.base.BaseActivity;
import com.yunshipei.common.wedigt.YspTitleBar;
import com.yunshipei.db.DatabaseUtil;
import com.yunshipei.common.Globals;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.UserInfo;
import com.yunshipei.enterplorer.R;
import com.yunshipei.model.NotifyInfo;
import com.yunshipei.model.SpeechRecognition;
import com.yunshipei.parser.SpeechXMLParser;
import com.yunshipei.ui.view.TouchTextView;
import com.yunshipei.utils.AlarmSet;
import com.yunshipei.utils.TtsUtil;

import java.util.ArrayList;
import java.util.List;

import io.rong.app.utils.StringUtilSub;
import io.rong.eventbus.EventBus;

public class WarnActivity extends BaseActivity implements TouchTextView.OnMyTouchEvent, View.OnClickListener {
    private static String TAG = WarnActivity.class.getSimpleName();
    // 语音识别对象
    private SpeechRecognizerExt mAsr;
    private Toast mToast;
    private TextView resultView;
    private TouchTextView voiceView;
    private LinearLayout asrCreate;                 //创建提醒的布局
    private View listViewLayout;                    //提醒列表
    private TextView moreText;                      //更多提醒
    private ListView listView;                      //消息提醒列表
    private RelativeLayout asrInfo;
    private NotificationAdapter adapter;
    private List<NotifyInfo> list = null;
    private DatabaseUtil dbu = null;
    private View addNotifi;
    private ImageView destoryList;
    private TtsUtil ttsUtil;                        //语音合成
    private UserInfo userInfo;

    NotifyInfo notifiInfo = null;
    SpeechRecognition speechRecognition = null;

    @Override
    protected void onResume() {
        super.onResume();
        list = dbu.queryNotifiAll(true, userInfo.getUuid());
        adapter.updateListView(list);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_warn);
        this.userInfo = (UserInfo) StringUtilSub.getEncodeBase64(YspPreferences.getInstance().getSharedPreferences().getString(Globals.YSP_USER_INFO, ""));
        dbu = new DatabaseUtil();
        initLayout();
        initData();
        showList(list);
        // 创建识别对象
        mAsr = SpeechRecognizerExt.getInstance(getApplicationContext());
        // 初始化引擎
        mAsr.initAsrEngine(mAsrListener, null);
        mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        ttsUtil = TtsUtil.getInstance();
    }

    /**
     * 初始化Layout。
     */
    private void initLayout() {
        resultView = (TextView) findViewById(R.id.warn_info);
        asrInfo = (RelativeLayout) findViewById(R.id.asr_info);
        voiceView = (TouchTextView) findViewById(R.id.btn_rcd);
        voiceView.setOnMyTouchEvent(this);
        asrCreate = (LinearLayout) findViewById(R.id.asr_create);
        listViewLayout = findViewById(R.id.list_view_layout);
        moreText = (TextView) findViewById(R.id.more);
        addNotifi = findViewById(R.id.add_notifi);
        listView = (ListView) findViewById(R.id.notification_list);

        destoryList = (ImageView) findViewById(R.id.destory_list);
        moreText.setOnClickListener(this);
        asrInfo.setOnClickListener(this);
        addNotifi.setOnClickListener(this);
        destoryList.setOnClickListener(this);
        showList();
    }

    private void initData() {
        list = new ArrayList<NotifyInfo>();
        list = dbu.queryNotifiAll(true, userInfo.getUuid());
        adapter = new NotificationAdapter(WarnActivity.this, list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.putExtra(NotifiDetailActivity.FORM, false);
                Bundle bundle = new Bundle();
                bundle.putSerializable("notifiInfo", list.get(position));
                intent.putExtras(bundle);
                intent.setClass(WarnActivity.this, NotifiDetailActivity.class);
                startActivity(intent);
            }
        });
    }


    int ret = 0;// 函数调用返回值

    private void showTip(final String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mToast.setText(str);
                mToast.show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        // 退出时释放连接
        mAsr.cancelRecognize();
        mAsr.destroy();
        ttsUtil.destory();
        super.onDestroy();
    }

    /**
     * 语音识别回调
     */
    private AsrListener mAsrListener = new AsrListener() {
        @Override
        public void onVolumeChanged(final int value) {
            if (voiceView != null)
                voiceView.setCurrentVoiceDb(value);
        }

        @Override
        public void onError(final com.iflytek.base.speech.adapter.Error error) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showTip("识别出错");
                }
            });
            voiceView.discornStop();
        }

        @Override
        public void onSpeechStart() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showTip("检测到前端点");
                }
            });
        }

        @Override
        public void onSpeechEnd() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showTip("检测到后端点");
                }
            });
        }

        @Override
        public void onResult(final AsrResult result) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (null != result) {
                        SpeechXMLParser sp = new SpeechXMLParser();
                        notifiInfo = new NotifyInfo();
                        speechRecognition = sp.parser(result.getResult());
                        notifiInfo.setSpeechRecognition(speechRecognition);
                        if (!speechRecognition.getFocus().equals("other")) {
                            long timeLong = speechRecognition.getDateTime().getFormatDate();
                            if (timeLong != 0) {
                                //设置闹钟提醒
                                int insertId = dbu.insertAlarm(notifiInfo);
                                AlarmSet as = new AlarmSet(WarnActivity.this);
                                long times = notifiInfo.getSpeechRecognition().getDateTime().getFormatDate();
                                notifiInfo.set_id(insertId);
                                long forwardTime = notifiInfo.countForwardTime();
                                as.setAlarm(notifiInfo, forwardTime, notifiInfo.get_id());
                                showCreatLayout(speechRecognition);
                                list.add(notifiInfo);
                                //插入数据库
                            } else {
                                showTip("提醒设置失败");
                            }
                        } else {
                            showTip("提醒设置失败");
                        }
                    } else {
                        Log.w(TAG, "recognizer result : null");
                    }
                    voiceView.discornStop();
                }
            });
        }

        @Override
        public void onRecordStart() {
        }

        @Override
        public void onRecordEnd() {
        }

        @Override
        public void onPartialResult(AsrResult result) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onInited() {
        }

        @Override
        public void onAddLexiconFinish(final String id, final int code,
                                       final String caller) {
        }

        @Override
        public void onBuildFinish(final String id, final int code,
                                  final String caller) {
        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.more:
                //显示列表
                showList(getList());
//                Toast.makeText(WarnActivity.this, "显示更多提醒", Toast.LENGTH_SHORT).show();
                break;
            case R.id.asr_info:
                //新创建的提醒
                showTip("显示提醒详细情况");
                break;
            case 111:
                mAsr.cancelRecognize();
                break;
            case R.id.add_notifi:
                /**
                 * add new notifi
                 */
                Intent intent = new Intent();
                intent.putExtra(NotifiDetailActivity.FORM, true);
                intent.setClass(WarnActivity.this, NotifiDetailActivity.class);
                startActivity(intent);
                break;
            case R.id.destory_list:
                Uri uri = Uri.parse("Enterplorer://" + getApplicationInfo().packageName).buildUpon()
                        .appendPath("Destory").appendQueryParameter("target", "time").build();
                Intent intent1 = new Intent();
                intent1.setData(uri);
                intent1.setClass(WarnActivity.this, AlarmSetActivity.class);
                startActivity(intent1);
                break;
            default:
                break;
        }
    }

    //开始识别
    @Override
    public void actionDownHandle() {
        ttsUtil.stopSpeech();
        resultView.setText(null);// 清空显示内容
        Intent asrIntent = new Intent();
        //引擎类型：网络
        asrIntent.putExtra(RecognizerIntent.EXT_ENGINE_TYPE, RecognizerIntent.ENGINE_WEB);
        // scence传入提醒业务场景：schedule
        mAsr.startRecognition(null, "schedule", 0, 0, asrIntent);
    }

    //停止识别
    @Override
    public void actionUpHandle() {
        mAsr.stopRecognize();
    }

    /**
     * 显示提醒列表
     * 隐藏创建列表
     */
    public void showList() {
        //隐藏创建布局
        asrCreate.setVisibility(View.GONE);
        //显示提醒列表
        listViewLayout.setVisibility(View.VISIBLE);
        /**
         * 在此做相关的信息加载
         */
    }

    public void showList(List<NotifyInfo> list) {
        //隐藏创建布局
        asrCreate.setVisibility(View.GONE);
        //显示提醒列表
        listViewLayout.setVisibility(View.VISIBLE);
        //更新列表
        adapter.updateListView(getList());
    }

    /**
     * 显示创建列表
     * 隐藏提醒列表
     */
    public void showCreatLayout() {
        asrCreate.setVisibility(View.VISIBLE);
        listViewLayout.setVisibility(View.GONE);
    }

    /**
     * 显示创建列表
     *
     * @param sp
     */
    public void showCreatLayout(SpeechRecognition sp) {
        String conStr = "提醒新建成功," + sp.getDateTime().getDateOrig()
                + sp.getDateTime().getTimeOrig() + "提醒您";
        asrCreate.setVisibility(View.VISIBLE);
        listViewLayout.setVisibility(View.GONE);
        TextView recognitionView, systemCon, asrContent, timeContent, asrAs;
        recognitionView = (TextView) findViewById(R.id.recognition_context);
        systemCon = (TextView) findViewById(R.id.system_analyze);
        asrContent = (TextView) findViewById(R.id.asr_content);
        timeContent = (TextView) findViewById(R.id.time_content);

        asrContent.setText(sp.getContent());
        systemCon.setText(conStr);
        recognitionView.setText(sp.getContent());
        timeContent.setText(sp.getDateTime().getTime() + "  " + sp.getDateTime().getDate());
        //语音播报
        ttsUtil.startSpeech(conStr);
    }

    public List<NotifyInfo> getList() {
        return this.list;
    }

    public NotificationAdapter getAdapter() {
        return this.adapter;
    }

    public void onEventMainThread(NotifyInfo notifiInfo) {
        list = dbu.queryNotifiAll(true, userInfo.getUuid());
        adapter.updateListView(list);
    }
}